package cn.weirdor.security.common.runer;

import cn.weirdor.security.common.utils.StringUtils;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DreamApplication {

    /**
     * Create an application context
     *
     * @param appName       application name
     * @param primarySource The sources
     * @param args          args the command line arguments
     * @return an application context created from the current state
     */
    public static ConfigurableApplicationContext run(String appName, Class<?> primarySource, String... args) {
        // 读取环境变量，使用spring boot的规则
        ConfigurableEnvironment environment = new StandardEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addFirst(new SimpleCommandLinePropertySource(args));
        propertySources.addLast(new MapPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, environment.getSystemProperties()));
        propertySources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, environment.getSystemEnvironment()));
        // 获取配置的环境变量
        String[] activeProfiles = environment.getActiveProfiles();
        // 判断环境:dev、test、prod
        List<String> profiles = Arrays.asList(activeProfiles);
        // 预设的环境
        List<String> presetProfiles = new ArrayList<>(Arrays.asList("dev", "test", "prod"));
        // 交集
        presetProfiles.retainAll(profiles);
        // 当前使用
        List<String> activeProfileList = new ArrayList<>(profiles);
        SpringApplicationBuilder builder = new SpringApplicationBuilder(primarySource);
        String profile;
        if (presetProfiles.isEmpty()) {
            // 默认dev开发
            profile = "dev";
            activeProfileList.add(profile);
            builder.profiles(profile);
        } else if (presetProfiles.size() == 1) {
            profile = presetProfiles.get(0);
        } else {
            // 同时存在dev、test、prod环境时
            throw new RuntimeException("同时存在环境变量:[" + StringUtils.join(activeProfiles) + "]");
        }
        System.err.println("----启动中，读取到的环境变量:[" + StringUtils.join(activeProfileList) + "]----");
        System.setProperty("dream.env", profile);
        System.setProperty("spring.application.name", appName);
        System.setProperty("spring.banner.location", "classpath:dream_banner.txt");
        return builder.run(args);
    }

}
